import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { Checkbox, Table, TableProps } from 'antd'
import { State } from '@/apps/panel/reducers'
import { getVarsInstance, createVarsFilter } from '@/common/varsFactory'
import { updateConfig } from '@/apps/panel/actions'
import './index.less'

type SizeType = TableProps<any>['size']

export default function VariableList() {

    const dispatch = useDispatch()
    const allVariables = useSelector((state: State) => state.variables)

    const config = useSelector((state: State) => state.config)
    const columns = [
        {
            title: 'Name',
            dataIndex: 'key',
            key: 'key',
            width: '40%'
        },
        {
            title: 'Value',
            dataIndex: 'value',
            key: 'value',
            render: (val: any) => JSON.stringify(val) || 'undefined'
        }
    ]
    const { showCommonInternalVariables, showAdvancedInternalVariables } = config
    const filter = createVarsFilter({
        withCommonInternal: showCommonInternalVariables,
        withAdvancedInternal: showAdvancedInternalVariables
    })
    const variables = allVariables.filter(variable => filter(variable.key))

    const tableConfig = {
        columns,
        dataSource: variables,
        pagination: undefined,
        bordered: true,
        size: 'middle' as SizeType,
        rowKey: 'key',
        rowClassName: (record: Record<string, any>) => {
            const vars = getVarsInstance()
            if (!vars) return ''
            return vars.isReadOnly(record.key) ? 'read-only' : ''
        }
    }

    return <div className="variable-content">
        <div className="variable-options">
            <Checkbox
                onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => dispatch(updateConfig({ showCommonInternalVariables: (e.target as HTMLInputElement).checked }) as any)}
                checked={config.showCommonInternalVariables}
            >
                显示通用<a href="https://rpa.yonyoucloud.com/help?help=internalvars" target="_blank">内部变量</a>
            </Checkbox>
            <Checkbox
                onClick={
                    (e: React.MouseEvent<HTMLInputElement, MouseEvent>) => dispatch(updateConfig({
                        showAdvancedInternalVariables: (e.target as HTMLInputElement).checked
                    }) as any)
                }
                checked={config.showAdvancedInternalVariables}
            >
                显示高级<a href="https://rpa.yonyoucloud.com/help?help=internalvars" target="_blank">内部变量</a>
            </Checkbox>
        </div>
        <Table {...tableConfig} />
    </div>
}